package com.it.gmall.user.controller;

import com.it.gmall.common.constant.RedisConst;
import com.it.gmall.common.result.Result;
import com.it.gmall.model.user.UserAddress;
import com.it.gmall.model.user.UserInfo;
import com.it.gmall.user.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping(("api/user/passport"))
public class UserController {
    @Autowired
    private UserService userService;
    @Autowired
    private RedisTemplate redisTemplate;

    // 用户登录
    @PostMapping("/login")
    public Result userLogin(@RequestBody UserInfo userInfo){
        // 1.验证用户名和密码是否正确
        UserInfo info = userService.userLogin(userInfo);
        if(null!=info){
            // 2.存在缓存中
            String uuid = UUID.randomUUID().toString();
            redisTemplate.opsForValue().set(RedisConst.USER_LOGIN_KEY_PREFIX+uuid,info.getId().toString(), RedisConst.USERKEY_TIMEOUT, TimeUnit.SECONDS);
            // 3.页面返回数据
            Map map = new HashMap<>();
            // 3.1 设置昵称
            map.put("nickName",info.getNickName());
            map.put("token",uuid);
            // 3.2 设置令牌
            return Result.ok(map);
        }else{
            // 返回错误信息
            return Result.fail("用户名或密码错误");
        }
    }

    // 获取用户的地址信息
    @GetMapping("/getUserAddress")
    public List<UserAddress> getUserAddress(HttpServletRequest request){
        return userService.getUserAddress(request);
    }
}
